package com.adityayadav.peekaboo;

import java.io.InputStream;
import java.net.Socket;
import java.net.URL;
import java.util.StringTokenizer;

import com.adityayadav.parallelism.core.ITask;
import com.adityayadav.parallelism.core.ThreadPool;

public class SocketAcceptorTask implements ITask {

	private Socket incoming = null;
	private ThreadPool pool = null;
	private MainJFrame mainJFrame = null;
	
	public SocketAcceptorTask(MainJFrame mainJFrame, ThreadPool pool, Socket incoming){
		this.pool = pool;
		this.incoming = incoming;
		this.mainJFrame = mainJFrame;
	}
	
	@Override
	public void commit() throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void initialize() throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void rollback() throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void run() throws Exception {
		InputStream is = incoming.getInputStream();
		HTTPRequestParser rp = new HTTPRequestParser();
		int numRead = 0;
		byte[] buffer = new byte[8192];
		while (true){
			numRead = is.read(buffer);
			byte[] data = new byte[numRead];
			System.arraycopy(buffer,0,data,0,numRead);
			rp.addToBuffer(data);
			byte[] l = rp.getALine();
			if (l != null){
				String line = new String(l);
				StringTokenizer st = new StringTokenizer(line," ");
				String method = st.nextToken();
				URL url = new URL(st.nextToken());
				String http = st.nextToken();
				String host = url.getHost();
				int port = url.getPort()==-1 ? url.getDefaultPort() : url.getPort();
				String path = url.getFile();
				
				//Create URL for the UI
				String uiURL = method+" "+url.getProtocol()+"://"+host+":"+port+url.getPath();
				mainJFrame.addSocket(uiURL, incoming);
				
				byte[] tosend = (method + " "+ path + " " + http+"\r\n").getBytes("US-ASCII");
				byte[] pending = rp.getBuffer();
				byte[] everythingtosend = new byte[tosend.length+pending.length];
				System.arraycopy(tosend,0,everythingtosend,0,tosend.length);
				System.arraycopy(pending,0,everythingtosend,tosend.length, pending.length);
				
				Socket outgoing = new Socket(host,port);
				outgoing.getOutputStream().write(everythingtosend);
				
				RecurringWorkerTask inProcessor = new RecurringWorkerTask(pool,incoming,incoming.getInputStream(), outgoing.getOutputStream());
				inProcessor.addToBuffer(everythingtosend);
				RecurringWorkerTask outProcessor = new RecurringWorkerTask(pool,incoming,outgoing.getInputStream(), incoming.getOutputStream());
				SocketRegistry.getInstance().put(incoming, new Processors(inProcessor, outProcessor));
				pool.addTask(inProcessor);
				pool.addTask(outProcessor);
				break;
			}
		}

		
	}

}
